package com.frx.sort;

import java.util.Arrays;

/**
 * Created with IDEA
 *
 * @author: xrf
 * @Date: 2019/8/26
 * @Time: 9:39
 */
public class QuickSort {

    public static void main(String[] args){
        int[] arr = {3,5,2,4,1,7};

        quickSort(arr,0,arr.length-1);
        System.out.println(Arrays.toString(arr));
    }

    public static void quickSort(int[] arr,int startIndex,int endIndex){
        if (startIndex >= endIndex){
            return;
        }
        //int partition = partition(arr,startIndex,endIndex);

        int partition = partition2(arr,startIndex,endIndex);
        quickSort(arr,startIndex,partition-1);
        quickSort(arr,partition+1,endIndex);
    }
    /**
     * 单边循环法
     * */
    public static int partition(int[] arr,int startIndex,int endIndex){

        int pivot = arr[startIndex];
        int mark = startIndex;
        for (int i = startIndex+1; i < endIndex; i++){
            if (arr[i] < pivot){
                mark++;
                int temp = arr[i];
                arr[i] = arr[mark];
                arr[mark] = temp;
            }
        }
        int temp = arr[mark];
        arr[mark] = pivot;
        arr[startIndex] = temp;
        return mark;
    }
    /** 双边循环法*/
    private static int partition2(int[] arr, int startIndex, int endIndex) {
        int left = startIndex;
        int right = endIndex;
        int pivot = arr[startIndex];
        while (left!=right){
            while (left < right && arr[right] > pivot){
                right--;
            }
            while (left < right && arr[left] <= pivot){
                left++;
            }


                int temp = arr[left];
                arr[left] = arr[right];
                arr[right] = temp;

        }
        arr[startIndex] = arr[left];
        arr[left] = pivot;
        return left;
    }

}
